<template>
  <div class="table-box">
    <ProTable ref="proTable" title="优惠券列表" row-key="id" :columns="columns" :request-api="getFoodCouponList">
      <!-- :request-auto="false" -->
      <!-- 表格 header 按钮 -->
      <template #tableHeader>
        <el-button v-auth="'add'" type="primary" :icon="CirclePlus" @click="toCreate(0)"> 新增优惠券 </el-button>
      </template>
      <template #parValue="scope">
        <el-text>{{ scope.row.typeId === 1 ? scope.row.parValue : "--" }}</el-text>
      </template>
      <!-- 表格操作 -->
      <template #operation="scope">
        <el-button v-auth="'edit'" type="primary" link :icon="EditPen" @click="toCreate(scope.row.id)"> 编辑 </el-button>
        <el-button v-auth="'delete'" type="primary" link :icon="Delete" @click="deleteAccount(scope.row)"> 删除 </el-button>
      </template>
    </ProTable>
  </div>
</template>

<script setup lang="tsx" name="coupon">
import { ref, onBeforeUpdate } from "vue";
import { Goods } from "@/api/interface";
import { useRouter, useRoute } from "vue-router";
import { useHandleData } from "@/hooks/useHandleData";
import ProTable from "@/components/ProTable/index.vue";
import { CirclePlus, Delete, EditPen } from "@element-plus/icons-vue";
import { ColumnProps, ProTableInstance } from "@/components/ProTable/interface";
import { getFoodCouponList, deleteFoodCoupon } from "@/api/modules/coupon";
import { getDicData } from "@/api/modules/system";

// 获取 ProTable 元素，调用其获取刷新数据方法（还能获取到当前查询参数，方便导出携带参数）
const proTable = ref<ProTableInstance>();

// 表格配置项
const columns: ColumnProps<Goods.ResGoodsCategoryList>[] = [
  { type: "index", label: "#", width: 60 },
  { sortable: true, prop: "name", label: "券名称", align: "left", minWidth: 120, search: { el: "input" } },
  {
    sortable: true,
    prop: "typeId",
    label: "券类型",
    align: "left",
    minWidth: 100,
    enum: () => getDicData("CouponType"),
    search: { el: "select" },
    fieldNames: { label: "title", value: "value" }
  },
  { sortable: true, prop: "parValue", label: "券面值", align: "left", minWidth: 100 },
  { sortable: true, prop: "validityDesc", label: "领取后有效期", align: "left", minWidth: 164 },
  { sortable: true, prop: "createTime", label: "创建时间", align: "left", minWidth: 164 },
  { sortable: true, prop: "validityObject", label: "使用生效期", align: "left", minWidth: 280 },
  { prop: "operation", label: "操作", width: 150, fixed: "right" }
];

// 跳转详情页面
const router = useRouter();
const route = useRoute();
const toCreate = (id?: number) => {
  if (id !== 0) {
    router.push({
      path: "/marketing/coupon-edit",
      query: {
        id: id
      }
    });
  } else {
    router.push(`/marketing/coupon-edit`);
  }
};

// 删除
const deleteAccount = async (params: Goods.ResGoodsCategoryList) => {
  await useHandleData(deleteFoodCoupon, { id: params.id }, `删除【${params.name}】优惠券`);
  proTable.value?.getTableList();
};
onBeforeUpdate(() => {
  if (!!route.query.upList) {
    proTable.value?.getTableList();
  }
});
</script>
